<template>
    <div class="main-content">
        <ElForm
            ref="searchFormRef"
            :model="searchForm"
            inline
            class="search-form"
            label-width="68px"
            label-position="left">
            <ElFormItem label="项目编号" prop="code">
                <ElInput
                    v-model="searchForm.code"
                    size="default"
                    placeholder="请输入"
                ></ElInput>
            </ElFormItem>
            <ElFormItem label="项目名称" prop="name">
                <ElInput
                    v-model="searchForm.name"
                    size="default"
                    placeholder="请输入"
                ></ElInput>
            </ElFormItem>
            <ElFormItem label="委托单位" prop="consignor">
                <ElInput
                    v-model="searchForm.consignor"
                    size="default"
                    placeholder="请输入"
                ></ElInput>
            </ElFormItem>
            <ElFormItem label="开工日期" prop="startDate">
                <el-date-picker
                    v-model="searchForm.startDate"
                    type="date"
                    size="default"
                    placeholder="请选择"
                    value-format="YYYY-MM-DD"
                />
            </ElFormItem>
            <ElFormItem label="验收日期" prop="deliveryDate">
                <el-date-picker
                    v-model="searchForm.deliveryDate"
                    type="date"
                    size="default"
                    placeholder="请选择"
                    value-format="YYYY-MM-DD"
                />
            </ElFormItem>
            <ElFormItem label="负责人" prop="manager">
                <ElInput
                    v-model="searchForm.manager"
                    size="default"
                    placeholder="请输入"
                >
                </ElInput>
            </ElFormItem>
            <ElFormItem label="项目状态" prop="status">
                <ElSelect
                    v-model="searchForm.status"
                    size="default"
                    clearable=""
                    placeholder="请选择"
                >
                    <ElOption
                        v-for="item in statusOps"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    ></ElOption>
                </ElSelect>
            </ElFormItem>

            <ElFormItem>
                <ElButton
                    size="default"
                    color="#4371EE"
                    @click="reset(false)"
                >
                    查询
                </ElButton>
                <ElButton
                    size="default"
                    plain=""
                    @click="reset(true)"
                >
                    重置
                </ElButton>
            </ElFormItem>
        </ElForm>
            <!-- </ElCol> -->
            <div class="btns">
                <ElButton
                    color="#4371EE"
                    class="add-btn"
                    v-permission="2"
                    size="default"
                    :icon="Plus"
                    @click="addShow = true"
                >
                    创建项目
                </ElButton>
            </div>
            <ElTable
                border
                id="userTable"
                class="table"
                :data="tableData"
                :style="{ height: `${maxTableHeight}px`, overflow: 'auto' }"
            >
                <ElTableColumn prop="code" label="项目编号" />
                <ElTableColumn prop="name" label="项目名称" />
                <ElTableColumn prop="consignor" label="委托单位" />
                <ElTableColumn prop="startDate" label="开工日期" />
                <ElTableColumn prop="deliveryDate" label="验收日期" />
                <ElTableColumn prop="manager" label="项目负责人" />
                <ElTableColumn prop="status" label="项目状态" >
                    <template #default="scope">
                        {{ statusOps.find(({ value }) => value == scope.row.status).label }}
                    </template>
                </ElTableColumn>

                <ElTableColumn  fixed="right" label="操作" width="250px">
                    <template #default="scope">
                        <ElButton

                        link
                        type="text"
                        size="default"
                        @click="goDetail(scope.row)"
                        >
                        详情
                        </ElButton>
                        <ElButton   v-permission="3" link type="text" size="default" @click="editFun(scope.row)">
                        编辑
                        </ElButton>
                        <ElButton  v-permission="4"  link type="text" size="default"  @click="editMember(scope.row)">
                        成员管理
                        </ElButton>
                        <ElButton  v-permission="4"  link type="text" size="default"  @click="handleDelete(scope.row)">
                        删除
                        </ElButton>
                    </template>
                </ElTableColumn>
            </ElTable>

            <ElPagination
                class="pagination"
                background
                layout="total,sizes,prev, pager, next,jumper"
                :total="total"
                :current-page="searchForm.pageNum"
                :page-sizes="[10, 20, 50, 100]"
                :page-size="searchForm.pageSize"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />

            <!--新增或编辑角色-->
            <ElDialog   class="main-dialog" v-model="addShow"  :title="addForm.id ? '编辑项目' : '创建项目'" width="480px">
                <div class="dialog-form">
                    <ElForm
                        ref="addFormRef"
                        :model="addForm"
                        :rules="rules"
                        label-width="80px"
                        label-position="left"
                    >
                        <ElFormItem label="项目编号" prop="code">
                            <el-input v-model="addForm.code" size="default" placeholder="请输入项目编号"  />
                        </ElFormItem>
                        <ElFormItem label="项目名称" prop="name">
                            <el-input v-model="addForm.name" size="default" placeholder="请输入项目名称"  />
                        </ElFormItem>
                        <ElFormItem label="委托单位" prop="consignor">
                            <el-input v-model="addForm.consignor" size="default" placeholder="请输入委托单位"  />
                        </ElFormItem>
                        <ElFormItem label="开工日期" prop="startDate">
                            <el-date-picker

                                v-model="addForm.startDate"
                                type="date"
                                size="default"
                                placeholder="请选择"
                                value-format="YYYY-MM-DD"
                            />
                        </ElFormItem>
                        <ElFormItem label="验收日期" prop="deliveryDate">
                            <el-date-picker
                            placeholder="请选择"
                                v-model="addForm.deliveryDate"
                                type="date"
                                size="default"
                                value-format="YYYY-MM-DD"
                            />
                        </ElFormItem>
                        <ElFormItem label="负责人" prop="manager">
                            <el-input v-model="addForm.manager" size="default" placeholder="请输入负责人"  />
                        </ElFormItem>

                        <ElFormItem label="项目状态">
                            <ElSelect
                                v-model="addForm.status"
                                size="default"
                                placeholder="请选择"
                            >
                                <ElOption
                                    v-for="item in statusOps"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                ></ElOption>
                            </ElSelect>
                        </ElFormItem>
                    </ElForm>
                </div>
                <template #footer>
                    <span  class="dialog-footer">
                        <ElButton size="default" @click="addShow = false">取 消</ElButton>
                        <ElButton color="#4371EE" size="default" @click="submitForm(addFormRef)">提 交</ElButton>
                    </span>
                </template>

            </ElDialog>

            <ElDialog   class="main-dialog" v-model="detailShow"  title="项目详情" width="700px">
                <div class="dialog-form">
                    <ul class="details">
                        <li class="details-item"><label>项目编号：</label> {{ details.code }}</li>
                        <li class="details-item"><label>项目名称：</label> {{ details.name }}</li>
                        <li class="details-item"><label>委托单位：</label> {{ details.consignor }}</li>
                        <li class="details-item"><label>开工日期：</label> {{ details.startDate }}</li>
                        <li class="details-item"><label>验收日期：</label> {{ details.deliveryDate }}</li>
                        <li class="details-item"><label>负责人：</label> {{ details.manager }}</li>
                        <li class="details-item"><label>项目状态：</label> {{  statusOps.find(({ value }) => value == details.status).label }}</li>
                        <li class="details-item"><label>项目成员：</label> </li>
                    </ul>
                    <ElTable
                        border
                        class="table"
                        :data="rightUserList"
                        style="margin-top: 10px;"
                        max-height="250
                        "
                    >
                        <ElTableColumn prop="userName" label="帐号" />
                        <ElTableColumn prop="realName" label="成员名称" />
                        <ElTableColumn prop="belongRole" label="项目角色" />
                        <ElTableColumn prop="createTime" label="加入日期" />


                    </ElTable>

                </div>

            </ElDialog>


            <ElDialog   class="main-dialog" v-model="memnberShow"  title="成员管理" width="1000px">
                <div class="dialog-form" style="display:flex;justify-content: space-between; align-items: stretch;">
                   <div style="width:490px;margin-right:20px;">
                        <p style="margin-bottom: 20px;;color:#000">未添加成员</p>
                        <ElButton
                            plain
                            :disabled="!addMemberForm.userIds.length"
                            class="add-btn"
                            color="#4371EE"
                            size="default"
                            @click="handleAddUser"
                        >
                        添加成员
                        </ElButton>
                        <ElTable
                            border
                            class="table"
                            :data="leftUserList"
                            style="margin-top: 10px;"
                            height="250"
                            @selection-change="handleAddUserChange"
                        >
                            <ElTableColumn type="selection" width="55px" />
                            <ElTableColumn prop="userName" label="帐号" />
                            <ElTableColumn prop="realName" label="成员名称" />
                            <ElTableColumn prop="belongRole" label="角色" />

                        </ElTable>
                   </div>
                   <div style="width:490px;">
                        <p style="margin-bottom: 20px;color:#000">已添加成员</p>
                        <ElButton
                        plain
                            class="add-btn"
                            color="#4371EE"
                            size="default"
                            @click="handleRemoveMember"
                            :disabled="!removeMemberForm.userIds.length"
                        >
                        移除成员
                        </ElButton>
                        <ElTable
                            border
                            class="table"
                            :data="rightUserList"
                            height="250"
                            style="margin-top: 10px;"
                            @selection-change="handleAddRemoveUserChange"
                        >
                            <ElTableColumn type="selection" width="55px" />
                            <ElTableColumn prop="userName" label="帐号" />
                            <ElTableColumn prop="realName" label="成员名称" />
                            <ElTableColumn prop="belongRole" label="项目角色" />
                            <ElTableColumn prop="createTime" label="加入日期" />


                        </ElTable>
                   </div>

                </div>

            </ElDialog>



    </div>
</template>

<script setup lang="ts">
import useTableSetting from '@/hooks/useTableSetting';
import { ref, onMounted, reactive, nextTick, watch } from 'vue';
import { getProjectList, addProject, editProject, getProjectUsers, userList, addProjectUser, removeProjectUser, deleteProject } from '@/api/index';

import { ElMessage, ElTree, FormInstance, ElMessageBox } from 'element-plus';

import { getFlatDeepTreeData } from '@/utils/common';
import { Search, Plus } from '@element-plus/icons-vue';
import { validateForm } from '@/helper/index';


const statusOps = [
    { label: '未开工', value: 0 },
    { label: '进行中', value: 1 },
    { label: '已结项', value: 2 }
];
const tableData: any = ref([]);

const allUserList = ref([]);

const getAllUserList = async () => {
    const res = await userList( { pageNum: 1, pageSize: 10000});
    allUserList.value = res.list;
};



const searchFormRef = ref<FormInstance>(null);



const searchForm = reactive<searchFormType>({
    code: '',
    name: '',
    consignor: '',
    startDate: '',
    deliveryDate: '',
    manager: '',
    status: '',
    pageNum: 1,
    pageSize: 20,
});
const total = ref<number>(0);


const rules = reactive({
    roleName: [{ required: true, message: '请输入角色名', trigger: 'blur' }],
});


const getList = async () => {
    try {
        const res: any = await getProjectList(searchForm);
        tableData.value = res.list;
        total.value = res.total;
    } catch (err) {}
};

const reset = (reset) => {
    if(reset) {
        searchFormRef.value.resetFields();
    }
    searchForm.pageNum = 1;
    getList();
};

const handleSizeChange = (rows: number) => {
    searchForm.pageNum = 1;
    searchForm.pageSize = rows;
    getList();
};
const handleCurrentChange = (page: number) => {
    searchForm.pageNum = page;
    getList();
};


const addShow = ref<boolean>(false);

const addFormRef = ref<FormInstance>(null);
const addForm = reactive<addRoleType>({
    id: '',
    code: '',
    name: '',
    consignor: '',
    startDate: '',
    deliveryDate: '',
    manager: '',
    status: '',
    mobilePhone: ''
});

const resetForm = (form) => {
    Object.keys(form).forEach(key => addForm[key] = '');
};

watch(
    addShow,
    val => {
        if(!val) {
            addFormRef.value.clearValidate();
            resetForm(addForm);
        }
    }
);

const submitForm = async (formEl: FormInstance | undefined) => {
    await validateForm(formEl);
    // const params = {
    //     ...addForm,
    //     startDate: addForm.date[0],
    //     deliveryDate: addForm.date[1],
    // };
    addForm.id ? await editProject(addForm) : await addProject(addForm);
    ElMessage.success('提交成功！');
    addShow.value = false;
    getList();
};



const editFun = async (row: any) => {
    addShow.value = true;
    Object.keys(row).forEach(key => {
        if(key in addForm) {
            addForm[key] = row[key];
        }
    });

};

// 详情

const detailShow = ref(false);
const details = ref([]);

const goDetail = (row) => {
    detailShow.value = true;
    getRightUser(row.id);
    details.value = JSON.parse(JSON.stringify(row));
};
const multiple = ref([]);
const memnberShow = ref(false);

const addMemberForm = reactive({
    id: '',
    userIds: []
});

const removeMemberForm = reactive({
    id: '',
    userIds: []
});

const leftUserList = ref([]);
const rightUserList = ref([]);

const getRightUser = async (id) => {
    const res = await getProjectUsers({ id: id ? id : addMemberForm.id});
    if(res && ref.length) {
        rightUserList.value = res;
    }
};

const updateUser = async () => {
    await getRightUser();
    const rightUserIds = rightUserList.value.filter(item => item &&item.userId).map(({ userId }) => userId);
    console.log(rightUserIds);
    leftUserList.value = allUserList.value.filter(({ userId }) => !rightUserIds.some(item => item == userId));

};

const editMember = async (row) => {
    if(!allUserList.value.length) {
        await getAllUserList();
    }
    removeMemberForm.id = row.id;
    addMemberForm.id = row.id;
    await updateUser();
    memnberShow.value = true;
};
const handleAddUserChange = (val) => {
    console.log(val);
    addMemberForm.userIds = val.map(({ userId, belongRole}) => ( { userId, belongRole }) );
};

const handleAddRemoveUserChange = (val) => {
    removeMemberForm.userIds = val.map(({ userId, belongRole}) => ( { userId, belongRole }) );
};

const handleAddUser = async () => {
    const params = addMemberForm.userIds.map(item => ({
        ...item,
        projectId: addMemberForm.id
    }));
    await addProjectUser(params);
    updateUser();
    ElMessage.success('添加成功！');
};

const handleRemoveMember = async () => {
    await ElMessageBox.confirm('确认要移除该人员吗？', '提示', {
        confirmButtonText: '确  定',
        cancelButtonText: '取  消',
        type: 'warning'
    });
    const params = removeMemberForm.userIds.map(item => ({
        ...item,
        projectId: removeMemberForm.id
    }));
    await removeProjectUser(params);
    updateUser();
    ElMessage.success('移除成功！');
};

const handleDelete = async (row) => {
    await ElMessageBox.confirm('确认要删除吗？', '提示', {
        confirmButtonText: '确  定',
        cancelButtonText: '取  消',
        type: 'warning'
    });
    await deleteProject({ id: row.id});
    ElMessage.success('删除成功！');
    reset();
};


onMounted(() => {

    getList();
});
const { maxTableHeight, setTableMaxHeight } = useTableSetting({ id: 'userTable', offsetBottom: 92 });
</script>

<style scoped lang="scss">
.main-content > .btns{
    margin:10px 0 20px;
}
.search-form{
   ::v-deep(){
    .el-input,.el-select{
        width: 265px !important;
    }
   }
}
</style>

